﻿using System;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;

namespace WJ.Infrastructure.Autofac
{
    public class MvcAutoRegister
    {
        public MvcAutoRegister(Action<ContainerBuilder> action,params Assembly[] controllerAssemblies)
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(controllerAssemblies);

            builder.RegisterModelBinders(controllerAssemblies);
            builder.RegisterModelBinderProvider();

            builder.RegisterModule<AutofacWebTypesModule>();

            builder.RegisterSource(new ViewRegistrationSource());

            builder.RegisterFilterProvider();

            

            var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToArray();

            var perRequestType = typeof(IPerRequest);
            builder.RegisterAssemblyTypes(assemblys)
                .Where(t => perRequestType.IsAssignableFrom(t) && t != perRequestType)
                .AsImplementedInterfaces()
                .InstancePerRequest();

            var perDependencyType = typeof (IPerDependency);
            builder.RegisterAssemblyTypes(assemblys)
                      .Where(t => perDependencyType.IsAssignableFrom(t) && t != perDependencyType)
                      .AsImplementedInterfaces()
                      .InstancePerDependency();

            var singleInstanceType = typeof (ISingleInstance);
            builder.RegisterAssemblyTypes(assemblys)
                      .Where(t => singleInstanceType.IsAssignableFrom(t) && t != singleInstanceType)
                      .AsImplementedInterfaces()
                      .SingleInstance();

            action(builder);

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            IoC.InitializeWith(new MvcDependencyResolver());
        }
    }
}